package com.ll.base.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.Properties;

@Slf4j
@Configuration
public class TransactionConfiguration {

    public static final String AOP_POINTCUT_EXPRESSION  = "execution(* com.ll.domain.**.biz.impl..*(..))";
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    private static final String PROPAGATION_NAME_CHANGE = "PROPAGATION_REQUIRED,-Exception";
    private static final String PROPAGATION_NAME_SELECT = "PROPAGATION_REQUIRED,-Exception";
    /**
     * 获取事务配置
     *
     * @return
     */
    public static Properties getAttrubites() {
        Properties attributes = new Properties();

        //查询
        attributes.setProperty("get*", PROPAGATION_NAME_SELECT);
        attributes.setProperty("query*", PROPAGATION_NAME_SELECT);
        attributes.setProperty("find*", PROPAGATION_NAME_SELECT);
        attributes.setProperty("select*", PROPAGATION_NAME_SELECT);

        //添加
        attributes.setProperty("add*", PROPAGATION_NAME_CHANGE);
        attributes.setProperty("insert*",PROPAGATION_NAME_CHANGE);
        attributes.setProperty("save*", PROPAGATION_NAME_CHANGE);
        attributes.setProperty("create*", PROPAGATION_NAME_CHANGE);

        //更新
        attributes.setProperty("update*",PROPAGATION_NAME_CHANGE);
        attributes.setProperty("modify*",PROPAGATION_NAME_CHANGE);
        attributes.setProperty("set*",PROPAGATION_NAME_CHANGE);
        //删除
        attributes.setProperty("delete*",PROPAGATION_NAME_CHANGE);
        attributes.setProperty("remove*",PROPAGATION_NAME_CHANGE);
        attributes.setProperty("*",PROPAGATION_NAME_SELECT);
        return attributes;

    }

    /**
     * 采用注解实例化的拦截器Bean，注入切面配置信息
     */
    @Bean
    public DefaultPointcutAdvisor defaultPointcutAdvisor(TransactionInterceptor ti){
        log.info("-----初始化事务管理----");
        ti.setTransactionManager(platformTransactionManager);
        ti.setTransactionAttributes(getAttrubites());
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut, ti);
    }
}